require "Common/define"
require "Logic/Config"
require "Common/functions"
---@class EquipManager
EquipManager = {};
local this = EquipManager;
local type = type;
local equipCfg = nil;
local weaponRankCfg = nil;
local weaponReset = nil;
local last_click_switch_suit = nil
---@type ClientEquipData[]
local tabAllEquip = {};
this.tabWeapon = {}
this.tempBreakData = {}
function EquipManager.init()
    equipCfg = dataTable.getDataTable("t_equip");
    weaponRankCfg = G.dataTable["t_weaponrank"];
    weaponReset = G.dataTable["t_weaponreset"];
    this.equipDataPool = {}
end
---@return ClientEquipData
function EquipManager.GetFromPool()
    if #this.equipDataPool > 0 then
        return table.remove(this.equipDataPool)
    end
    return ClientEquipData.New(0, 0, 0)
end
---@param equip ClientEquipData
function EquipManager.ReturnToPool(equip)
    if not equip then
        return
    end
    if #this.equipDataPool > 100 then
        return
    end
    equip:Set(0, 0, 0)
    table.insert(this.equipDataPool, equip)
end
--获取背包所有装备列表
function EquipManager.getEquipListByMinQuality(list, maxQuality)
    list = list or {};
    for k, v in pairs(tabAllEquip) do
        if (v.partnerId == nil or tonumber(v.partnerId) == 0) and v.quality <= maxQuality then
            table.insert(list, v);
        end
    end
    return list;
end
--获取背包所有装备列表
function EquipManager.getEquipList(list, ignoreClone)
    list = list or {};
    for k, v in pairs(tabAllEquip) do
        if v.partnerId == nil or tonumber(v.partnerId) == 0 then
            if ignoreClone then
                table.insert(list, v);
            else
                table.insert(list, clone(v));
            end
        end
    end
    return list;
end

--获取英雄装备列表
function EquipManager.getHeroEquipList(partnerId, ignoreClone)
    local list = {};
    for k, v in pairs(tabAllEquip) do
        if v.partnerId ~= nil and v.partnerId == tostring(partnerId) then
            if ignoreClone then
                table.insert(list, v)
            else
                table.insert(list, clone(v));
            end
        end
    end
    return list;
end

--获取英雄装备列表
function EquipManager.getAllHeroEquipListKeyPartnerId()
    local list = {}
    for k, v in pairs(tabAllEquip) do
        if v and v.partnerId ~= nil then
            if list[v.partnerId] == nil then
                list[v.partnerId] = {}
            end
            table.insert(list[v.partnerId], clone(v))
        end
    end
    return list
end

function EquipManager.PreviewBreak(equipId)
    local data = {}
    local isCan = true
    local cfg = equipCfg[tostring(equipId)]
    while cfg.f_QualityUpTarget ~= 0 and isCan do
        local itemId = cfg.f_QualityUpCost[1][1]
        local needNum = cfg.f_QualityUpCost[1][2]
        if logicMgr.ItemManager.getItemCountbyModelId(itemId) - (this.tempBreakData[itemId] or 0) >= needNum then
            data["targetId"] = cfg.f_QualityUpTarget
            if not data["items"] then
                data["items"] = {}
            end
            if not data["items"][itemId] then
                data["items"][itemId] = needNum
            else
                data["items"][itemId] = data["items"][itemId] + needNum
            end
            if not this.tempBreakData[itemId] then
                this.tempBreakData[itemId] = needNum
            else
                this.tempBreakData[itemId] = this.tempBreakData[itemId] + needNum
            end
            cfg = equipCfg[tostring(cfg.f_QualityUpTarget)]
        else
            isCan = false
        end
    end
    return data
end
--获取部位装备列表
function EquipManager.getEquipbyPart(equipPart, curHeroId)
    local list = {};
    for k, v in pairs(tabAllEquip) do
        if v.part == equipPart and not this.isCurHero(curHeroId, v.partnerId) then
            table.insert(list, clone(v));
        end
    end
    return list;
end

--获取当前英雄在当前部位的装备
function EquipManager.GetCurrentEquipment(heroId, part)
    for _, value in pairs(tabAllEquip) do
        if value.part == part and this.isCurHero(heroId, value.partnerId) then
            return value
        end
    end
    return nil
end

--判断是否当前英雄
function EquipManager.isCurHero(curHeroId, parnterId)
    if curHeroId == tostring(parnterId) then
        return true;
    else
        return false;
    end
end
function EquipManager.GetPower(equipInfo)
    if not equipInfo then
        return 0
    end
    return EquipManager.CalcEquipPowerByItemID(equipInfo.itemModelId, equipInfo.curRfLevel);

    --[[
    local equip = equipCfg[tostring(equipInfo.itemModelId)]
    if not equip then return 0 end
    local allAttrs = {}
    local attrs = decodeJsonStrToTabel(equipInfo["baseAttr"]);
    if attrs then
        for i=1,#attrs do
            for key, value in pairs(attrs) do
                if type(value) == "number" then
                    allAttrs[key] = value
                else
                    allAttrs[ value[1] ] = value[2]
                end
            end
        end
    end
    if equipInfo.curRfLevel and equipInfo.curRfLevel > 0 then
        local refineCfg = dataTable.getDataTableByMultiId("t_equiprefine", equipInfo.itemModelId, equipInfo.curRfLevel)
        if refineCfg then
            if not string.IsNilOrEmpty(refineCfg.f_EquipRefineAttribute) then
                attrs = decodeJsonStrToTabel(refineCfg.f_EquipRefineAttribute)
                for k,v in pairs(attrs) do
                    local _type = v[1]
                    local value = v[2]
                    if allAttrs[_type] then
                        allAttrs[_type] = allAttrs[_type] + value
                    else
                        allAttrs[_type] = value
                    end
                end
            end
        end
    end
    return logicMgr.HeroManager.processPower(allAttrs,equip.f_EquipHeroType);
    ]]
end

function EquipManager.CalcEquipPowerByUID(itemId)
    local itemData = tabAllEquip[tostring(itemId)];
    if itemData ~= nil then
        local refinePara = G.dataTable["t_global"]["550"][2];

        return math.floor(dataTable.getDataTableByStringId("t_Equip",itemData["itemModelId"],"f_EquipPower") * (10000 + refinePara * equip.curRfLevel) / 10000);
    end
    return 0;
end

function EquipManager.CalcEquipPowerByItemID(id, refeineLv)
    refeineLv = refeineLv or 0;
    if dataTable.getDataTableByStringId("t_Equip",id) ~= nil and refeineLv >= 0 then
        local refinePara = G.dataTable["t_global"]["550"][2];
        return math.floor(dataTable.getDataTableByStringId("t_Equip",id,"f_EquipPower") * (10000 + refinePara * refeineLv) / 10000);
    end
    return 0
end

function EquipManager.addItemData(itemDB, sourceCode, params, partnerId)


    --local equip = equipCfg[tostring(itemData.itemModelId)];
    --if equip ~= nil then
    --    itemData["name"] = getLanguage(equip.f_EquipName);
    --    itemData["tabType"] = EnumConst.ItemTableEnum.Equip;
    --    itemData["itemType"] = EnumConst.ItemTypeEnum.Equip;
    --    itemData["heroType"] = equip.f_EquipHeroType;
    --    itemData["icon"] = equip.f_EquipSuitlcon;
    --    itemData["level"] = equip.f_EquipLv;
    --    itemData["part"] = equip.f_EquipType;
    --    itemData["partName"] = getLanguage("EquipType"..equip.f_EquipType);
    --    itemData["quality"] = equip.f_EquipQuality;
    --    itemData["suit"] = equip.f_EquipSuit;
    --    itemData["desc"] = getLanguage(equip.f_EquipDesc);
    --    itemData["baseAttr"] = equip.f_EquipBasic;
    --    itemData["attribute"] = {};
    --    itemData["suitnum"] = 0;
    --    local attrs = decodeJsonStrToTabel(itemData["baseAttr"]);
    --    if attrs then
    --        for i=1,#attrs do
    --            for key, value in pairs(attrs) do
    --                if type(value) == "number" then
    --                    itemData["attribute"][key] = value
    --                else
    --                    itemData["attribute"][value[1]] = value[2]
    --                end
    --             end
    --        end
    --    end
    --    itemData["random"] = {};
    --    itemData["power"] = this.GetPower(itemData)--logicMgr.HeroManager.processPower(itemData["attribute"],equip.f_EquipHeroType);
    --end
    local _lastCount = 0
    local _itemId = tostring(itemDB.itemId)
    local itemData = tabAllEquip[_itemId]
    if itemData then
        _lastCount = itemData.num
        this.delItemData(itemData.itemId, -1)
    end
    local itemData = this.GetFromPool()
    itemData:Set(itemDB.itemId, itemDB.itemModelId, itemDB.num, true)
    if itemData.isInvalid then
        this.ReturnToPool(itemData)
        return
    end
    itemData:SetTabType(EnumConst.ItemTableEnum.Equip)
    itemData:SetPartnerId(partnerId)
    if itemDB.parameters ~= nil then
        local refine = decodeJsonStrToTabel(itemDB.parameters);
        itemData:SetRefine(tonumber(refine["STRENGTH_LEVEL"]), tonumber(refine["STRENGTH_EXP"]))
    end
    itemData:SetPower(this.GetPower(itemData))
    TAManager.TrackItemEvent(_itemId, itemData.itemModelId, itemData.num, _lastCount, sourceCode, params)
    tabAllEquip[itemData.itemId] = itemData
end
--初始化装备信息
function EquipManager.InitEquip(itemDB)
    local itemData = this.GetFromPool()
    itemData:Set(itemDB.itemId, itemDB.itemModelId, itemDB.num, true)
    itemData:SetTabType(EnumConst.ItemTableEnum.Equip)
    if itemDB.parameters ~= nil then
        local refine = decodeJsonStrToTabel(itemDB.parameters);
        itemData:SetRefine(tonumber(refine["STRENGTH_LEVEL"]), tonumber(refine["STRENGTH_EXP"]))
    end
    itemData:SetPower(this.GetPower(itemData))
    return itemData
end
function EquipManager.GetSuitCfgByEquipId(equipId)
    local cfg = dataTable.getDataTableByStringId("t_equip", equipId)
    if not cfg then
        return nil
    end
    local suit = dataTable.getDataTableByMultiId("t_equipsuit", cfg.f_EquipSuit, cfg.f_EquipHeroType, cfg.f_EquipQuality)
    return suit
end

--获得激活的2件套suit，4件套suit
function EquipManager.GetActiveSuitByEquipId(partnerId, equipId, equiplist, isother)
    local curEquipCfg = dataTable.getDataTableByStringId("t_equip", equipId)
    if not curEquipCfg then
        return 0, nil, nil
    end
    if curEquipCfg.f_EquipSuit == 0 then
        return 0, nil, nil
    end
    local swearEquips = nil
    if isother then
        swearEquips = equiplist
    else
        swearEquips = logicMgr.EquipManager.getHeroEquipList(partnerId, true)
    end
    local _tempList = TablePool.Get()
    local totalCount = 0
    local minQ = curEquipCfg.f_EquipQuality
    local highQ = curEquipCfg.f_EquipQuality
    local twoQ = 0
    local fourQ = 0
    local qua =   {}
    for key, value in pairs(swearEquips) do
        if isother then
            local config_Other = dataTable.getDataTableByStringId("t_equip", value.itemModelId)
            value.suit = config_Other.f_EquipSuit
            value.quality = config_Other.f_EquipQuality
        end
        if value.suit == curEquipCfg.f_EquipSuit then
            table.insert(qua,value.quality)
            local count = _tempList[value.quality]
            if not count then
                count = 0
            end
            count = count + 1
            _tempList[value.quality] = count
            totalCount = totalCount + 1
            if minQ > value.quality then
                minQ = value.quality
            end
            if highQ < value.quality then
                highQ = value.quality
            end
            if count >= 2 and twoQ < value.quality then
                twoQ = value.quality
            end
            if count >= 4 and fourQ < value.quality then
                fourQ = value.quality
            end
        end
    end
    local twoSuit, fourSuit
    if totalCount >= 2 and twoQ == 0 then
        twoQ = minQ
    end
    if totalCount >= 4 and fourQ == 0 then
        fourQ = minQ
    end
    if totalCount >=3 then
        table.sort(qua,function(a,b)
            return a > b
        end)
        twoQ = qua[2]
    end
    twoSuit = dataTable.getDataTableByMultiId("t_equipsuit", curEquipCfg.f_EquipSuit, curEquipCfg.f_EquipHeroType, twoQ)
    fourSuit = dataTable.getDataTableByMultiId("t_equipsuit", curEquipCfg.f_EquipSuit, curEquipCfg.f_EquipHeroType, fourQ)
    TablePool.Release(_tempList)
    return totalCount, twoSuit, fourSuit, minQ, highQ
end
function EquipManager.GetMaxRefineLevel(equipId)
    local cfgs = dataTable.getDataTableByMultiId("t_equiprefine", equipId)
    if not cfgs then
        return 0
    end
    return table.getn(cfgs) - 1
end
function EquipManager.GetRefineLevelExp(equipId, curLevel, curExp, totalExp)
    local cfgs = dataTable.getDataTableByMultiId("t_equiprefine", equipId)
    if not cfgs then
        return
    end
    for k, v in pairs(cfgs) do

    end
end
--属性名
function EquipManager.GetAttrName(attrId)
    return getLanguage(string.format(Config.LangAttribute, attrId));
end
--属性值 （值、百分比）
function EquipManager.GetAttrValue(attrId, attrValue)
    return this.formatAttr(attrId, attrValue);
end
function EquipManager.formatAttr(attrId, attrValue)
    local attrType = 1
    local cfg = dataTable.getDataTableByStringId("t_attributelibrary", attrId)
    if cfg then
        attrType = cfg["f_AttributeType"];
    end
    if attrType == 2 then
        return string.format("%0.1f%%", tostring(attrValue / 100));
    else
        return attrValue;
    end
end
function EquipManager.AddWeapon(db)
    local data = this.tabWeapon[tostring(db.partnerId)]
    if not data then
        data = {}
    end
    data.weaponId = db.weaponId;
    data.partnerId = db.partnerId;
    data.level = db.level;
    data.attiredId = db.attiredId;
    data.items = db.items
    if db.rank == nil or db.rank <= 0 then
        db.rank = 1;
        logError("服务器发送专武rank为空,partnerId:"..db.partnerId);
    end
    data.rank = db.rank
    data.costs = db.costs
    this.tabWeapon[tostring(db.partnerId)] = data
end
---@传入专武熟悉设置专武icon表现
function EquipManager.SetWeaponRectIcon(obj, data, partnerId)
    local img_Icon = obj:GetChild("icon")
    local img_Quality = obj:GetChild("quality")
    local img_Frame = obj:GetChild("frame")
    local obj_Add = obj:GetChild("add")
    local txt_Level = obj:GetChild("level")
    local txt_Strength = obj:GetChild("strength")
    local maxCtrl = obj:GetController("MaxLevel")

    img_Icon.visible = false
    img_Quality.visible = false
    img_Frame.visible = false
    txt_Level.visible = false
    txt_Strength.visible = false
    obj_Add.visible = true
    local heroCfg = HeroManager.getHeroDatabyPartnerId(partnerId);
    if not heroCfg then
        maxCtrl.selectedIndex = 0;
        return
    end
    local weaponShowConfig = this.getWeaponShowCfg(heroCfg.partnerModelId, data.rank,true);
    local weaponID = 150000 + tonumber(heroCfg.partnerModelId)
    local weaponConfig = G.dataTable["t_weapon"][tostring(weaponID)];
    if data ~= nil then
        if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.HeroWeapon, false, nil, { heroId = data.partnerId }) then
            if data.level < weaponConfig.f_MaxLevel and data.level ~= 0 then
                txt_Level.visible = true;
                txt_Level.text = data.level
                maxCtrl.selectedIndex = 1;
            else
                maxCtrl.selectedIndex = 2;
            end
            if weaponShowConfig.f_IconId then
                img_Icon.visible = true
                img_Icon.url = "ui://ItemAtlas/" .. weaponShowConfig.f_IconId;
                if data.rank ~= nil then
                    img_Quality.visible = true
                    img_Frame.visible = true
                    img_Frame.url = EnumConst.AtlasPath.ICONAtlas .. Config.IconFrame[tonumber(data.rank)]
                    img_Quality.url = EnumConst.AtlasPath.ICONAtlas .. Config.IconQuality[tonumber(data.rank)];
                end
            end
        else
            maxCtrl.selectedIndex = 0;
        end
    end


end
---@return 通过modelId获得专武等级
function EquipManager.getWeaponLevelByModelId(modelId, isAll)
    local heroData = logicMgr.HeroManager.getHeroDatabyModelId(modelId, true);
    if heroData then
        local data = this.tabWeapon[tostring(heroData.partnerId)]
        if data then
            if not isAll then
                return data.level, data.rank;
            else
                return data.rank, data
            end
        end
    end
    return 0;
end

---@return 通过英雄modelId和专武rank获得专武展示皮肤ID
function EquipManager.getWeaponShowIdByRank(modelId, rank)
    if modelId and rank then
        modelId = tonumber(modelId)
        rank = tonumber(rank)
        for k,v in pairs(G.dataTable["t_weapon"]) do
            if v.f_HeroID == modelId then
                local weaponShowInfos = decodeJsonStrToTabel(v.f_WeaponShow)
                if weaponShowInfos then
                    for m,n in pairs(weaponShowInfos) do
                        if n[1] == rank then
                            return n[2]
                        end
                    end
                end
            end
        end
    end
    return nil
end

---@return 通过英雄modelId和专武品质累加获得重置锻造返还物品
function EquipManager.getWeaponRefineResetByLevel(modelId, rank)
    if modelId and rank and tonumber(modelId) and tonumber(rank) then
        modelId = tonumber(modelId)
        rank = tonumber(rank)
        local itemList = {}
        for k,v in pairs(weaponRankCfg) do
            if tonumber(v.f_HeroId) == modelId and v.f_WeaponRank <= rank then
                local tempItems = decodeJsonStrToTabel(v.f_RankUpCost) or {}
                for m, n in pairs(tempItems) do
                    if itemList[n[1]] == nil then
                        itemList[n[1]] = n[2]
                    else
                        itemList[n[1]] = itemList[n[1]] + n[2]
                    end
                end
            end
        end
        return itemList
    end
    return nil
end

---@return 通过英雄modelId和专武品阶获得锻造升级消耗物品
function EquipManager.getWeaponRefineUpdateCostByRank(modelId, rank)
    if modelId and rank and tonumber(modelId) and tonumber(rank) then
        modelId = tonumber(modelId)
        rank = tonumber(rank)
        local itemList = {}
        for k,v in pairs(weaponRankCfg) do
            if tonumber(v.f_HeroId) == modelId and v.f_WeaponRank == rank then
                local tempItems = decodeJsonStrToTabel(v.f_RankUpCost) or {}
                return tempItems
            end
        end
        return itemList
    end
    return nil
end

---@return 通过英雄modelId和专武等级获得重置专武返还物品
function EquipManager.getWeaponResetByLevel(level)
    if level and tonumber(level) then
        local itemMap = {}
        local itemList = G.dataTable["t_weaponreset"][tostring(level)].f_ReturnItem or {}
        if itemList and type(itemList) == "table" then
            for k,v in pairs(itemList) do
                if itemMap[v[1]] == nil then
                    itemMap[v[1]] = v[2]
                else
                    itemMap[v[1]] = itemMap[v[1]] + v[2]
                end
            end
            return itemMap
        end
    end
    return nil
end

---@class 根据modelId，设置专武皮肤
---@param isSelf是否是自己英雄的实际情况
---@level 不是自己的英雄、或者不是自己当前情况时，直接传等级
function EquipManager.setWeaponSkin(skeletonGo, partnerModelId, isSelf, level)
    --有皮肤的英雄，从skin1开始，没有皮肤，就用default
    local quality
    local heroCfg = G.dataTable["t_hero"][tostring(partnerModelId)]
    if heroCfg == nil then
        logError("设置专武皮肤找不到英雄,partnerModelId:" .. (partnerModelId or -123));
        return ;
    end
    local skinName = (G.dataTable["t_roleconfig"][heroCfg.f_HeroModel] or {}).skin;
    if level == nil then
        level = 1
    end
    quality = level
    if skinName ~= nil and skinName ~= '' then

        if isSelf then
            level, quality = logicMgr.EquipManager.getWeaponLevelByModelId(partnerModelId);
            --print("英雄id==, 专武等级===", partnerModelId, level)
        end
        if quality == 0 then
            quality = 1
        end
        local tempName = EquipManager.getWeaponShowCfg(partnerModelId, quality)
        if tempName and table.getn(tempName) ~= 0 then
            Util.SetSkin(skeletonGo, tempName.f_SpineSkin);
        else
            Util.SetSkin(skeletonGo, "skin1");
        end
    else
        Util.SetSkin(skeletonGo, "default");
    end
end
function EquipManager.getWeaponShowCfg(partnerModelId, level,isShowWeapon)
    if not level or level < 1 then
        level = 1
    end
    if partnerModelId == 400 then
        partnerModelId = 40;--千棘分身要使用千棘的专武
    end
    local skin = SkinManager.getHeroSkinSrvInfo(partnerModelId)
    if table.getn(skin) ~= 0  and not isShowWeapon then
        return {}
    end
    local weaponId = 150000 + partnerModelId
    local weaponData = G.dataTable["t_weapon"][tostring(weaponId)]
    local minLevel = 0
    local minShowId = 0
    if weaponData then
        for i = 1, #weaponData.f_WeaponShow do
            local item = weaponData.f_WeaponShow[i];
            if item[1] <= level and item[1] > minLevel then
                minLevel = item[1]
                minShowId = item[2]
            end
        end
    end
    local wpShowData = G.dataTable["t_weaponshow"][tostring(minShowId)]
    if wpShowData then
        return wpShowData
    end
    return {}
end

--更新物品数量
function EquipManager.setItemData(itemId, num, sourceCode, params)
    local data = tabAllEquip[tostring(itemId)]
    if data then
        TAManager.TrackItemEvent(data.itemId, data.itemModelId, num, data.num, sourceCode, params)
        data:SetNum(num)
    end
end

function EquipManager.delItemData(itemId, sourceCode, params)
    itemId = tostring(itemId)
    local data = tabAllEquip[itemId]
    if data then
        TAManager.TrackItemEvent(data["itemId"], data["itemModelId"], 0, tonumber(data["num"]), sourceCode, params)
        tabAllEquip[itemId] = nil
        this.ReturnToPool(data)
    end
end

--获取某装备信息
---@return ClientEquipData
function EquipManager.getEquipbyId(itemId, ignoreClone)
    itemId = tostring(itemId)
    local data = tabAllEquip[itemId]
    if not data then
        return nil
    end
    if ignoreClone then
        return data
    else
        return clone(data);
    end
end
function EquipManager.getEquipCountById(itemId)
    itemId = tostring(itemId)
    local data = tabAllEquip[itemId]
    if not data then
        return 0
    end
    return data.num
end

function EquipManager.IsHaveEquipByPartnerId(partnerId)
    for k, v in pairs(tabAllEquip) do
        if v["partnerId"] == tostring(partnerId)then
            return true
        end
    end
    return false;
end

--获取某部位装备
function EquipManager.getEquip(partnerId, equipIndex, needClone)
    for k, v in pairs(tabAllEquip) do
        if v["partnerId"] == tostring(partnerId) and v["part"] == equipIndex then
            if needClone then
                return clone(v);
            else
                return v;
            end
        end
    end
    return nil;
end

--删除某部位装备
function EquipManager.delEquip(partnerId, equipIndex)
    for k, v in pairs(tabAllEquip) do
        if v["partnerId"] == tostring(partnerId) and v["part"] == equipIndex then
            tabAllEquip[v.itemId] = nil
            this.ReturnToPool(v)
            break ;
        end
    end
end
--获取卸下的装备
function EquipManager.GetUnwearEquipment(equipIndex)
    for key, item in pairs(tabAllEquip) do
        if item["part"] == equipIndex then
            return item
        end
    end
    return nil
end


--获取部位未穿戴最优装备
function EquipManager.getBestEquipbyPart(equip, equipPart, heroType)
    -- 限制等级大于0时，取装备不能超过该等级  有职业限时时，只取对应推荐职业的装备
    local seekEquip = logicMgr.EquipManager.getAllEquipbyPart(equipPart, heroType, false);

    if seekEquip ~= nil then--and (equip == nil or equip.suit == 0 or equip.suit == seekEquip1.suit) then
        if equip == nil or equip.quality < seekEquip.quality then
            return seekEquip
        elseif equip.quality == seekEquip.quality then
            local equipLv = equip.curRfLevel
            local seekEquipLv1 = seekEquip.curRfLevel
            if equipLv < seekEquipLv1 then
                return seekEquip
            end
        end
    end
    return nil
end

--获取部位所有装备
function EquipManager.getAllEquipsByPart(equipPart)
    local list = {}
    for k, item in pairs(tabAllEquip) do
        if item.part == equipPart then
            table.insert(list, clone(item))
        end
    end
    -- table.sort(list, function(a,b)
    --     return a.power > b.power
    -- end)

    return list
end

--获取部位未穿戴所有装备
function EquipManager.getAllEquipbyPart(equipPart, heroType, needClone)
    -- 限制等级大于0时，取装备不能超过该等级  有职业限时时，只取对应推荐职业的装备
    local list = {};
    local best_power = 0
    local curHeroType = (heroType ~= nil and heroType > 0) and heroType or 0;
    for k, item in pairs(tabAllEquip) do
        --   if item.power > best_power then
        if item.part == equipPart and (item.partnerId == nil or tonumber(item.partnerId) == 0) then
            if (curHeroType == 0 or item["heroType"] == curHeroType) then
                if needClone then
                    table.insert(list, clone(item));
                else
                    table.insert(list, item)
                end

                -- best_power = item.power
            end
        end
        --  endsuit
    end
    local best = list[1]

    for i = 2, #list do
        local e = list[i]
        if e.quality > best.quality then
            best = e
        elseif e.quality == best.quality and e.curRfLevel > best.curRfLevel then
            best = e
        end
    end

    return best
end



--通过modelid获取装备位置
function EquipManager.getEquipPartbyModelId(itemModelId)
    local part = math.fmod(Mathf.Floor(itemModelId / 10000), 10);
    return part;
end

--通过modelid获取装备位置
function EquipManager.setEquipRefine(partnerId, itemId, level, exp)
    for k, item in pairs(tabAllEquip) do
        if item["partnerId"] == tostring(partnerId) and item["itemId"] == tostring(itemId) then
            --装备精炼埋点
            local _equipRefineDic = {}
            _equipRefineDic.equip_id = tostring(itemId)
            _equipRefineDic.current_refine_level = tonumber(level)
            _equipRefineDic.previous_level = tostring(item["curRfLevel"])
            _equipRefineDic.current_equipexp = tonumber(exp)
            _equipRefineDic.previous_equipexp = tostring(item["exp"])
            TAManager.TrackByDictionary("equip_refine", _equipRefineDic)
            item:SetRefine(tonumber(level), tonumber(exp))
            break ;
        end
    end
end

--通过modelid获取装备位置
function EquipManager.changeEquip(partnerId, otherId, equipPart)
    local partnerEquip = nil;
    local otherEquip = nil;
    for k, item in pairs(tabAllEquip) do
        if item["partnerId"] == tostring(partnerId) and item["part"] == equipPart then
            partnerEquip = item;
        end
        if item["partnerId"] == tostring(otherId) and item["part"] == equipPart then
            otherEquip = item;
        end
    end

    if partnerEquip ~= nil then
        partnerEquip["partnerId"] = otherId;
    end
    if otherEquip ~= nil then
        otherEquip["partnerId"] = partnerId;
    end

end

--获取装备静态数据
function EquipManager.getEquipConstDatabyModelId(itemModelId)
    local item = equipCfg[tostring(itemModelId)];
    if item ~= nil then
        local itemData = {};
        itemData["itemModelId"] = item.f_EquipId
        itemData["name"] = getLanguage(item.f_EquipName);
        itemData["itemType"] = EnumConst.ItemTableEnum.Equip;
        itemData["quality"] = item.f_EquipQuality;
        itemData["icon"] = item.f_EquipSuitlcon;
        itemData["desc"] = getLanguage(item.f_EquipDesc);
        itemData["tabType"] = EnumConst.ItemTableEnum.Equip;
        itemData["heroType"] = item.f_EquipHeroType;
        itemData["level"] = item.f_EquipLv;
        itemData["part"] = item.f_EquipType;
        itemData["partName"] = getLanguage("EquipType" .. item.f_EquipType);
        itemData["suit"] = item.f_EquipSuit;
        itemData["baseAttr"] = item.f_EquipBasic;
        return itemData;
    end
    return nil;
end

function EquipManager.GetQuality(modelId)
    local item = equipCfg[tostring(modelId)];
    if item ~= nil then
        return item.f_EquipQuality;
    end
    return 1
end
--装备没有白色
function EquipManager.GetQualityFramePath(quality)
    return EnumConst.AtlasPath.ICONAtlas .. Config.IconFrame[tonumber(quality)]
end
--装备没有白色
function EquipManager.GetQualityBGPath(quality)
    return EnumConst.AtlasPath.ICONAtlas .. Config.IconQuality[tonumber(quality)]
end

--获取上次转换时间
function EquipManager.getLastSendSwitchTime()
    local temp = last_click_switch_suit
    last_click_switch_suit = UnityEngineTime.realtimeSinceStartup
    return temp
end

--- 当前装备推荐英雄数据列表,只读,禁止更改列表数据!!!
function EquipManager.GetNeedEquipHeroListByData(equipData)
    if equipData == nil then
        return {};
    end
    local list = {};
    local curEquipData;
    local tempOwner = logicMgr.HeroManager.getOwnerHeroListReadOnly();
    for k, v in pairs(tempOwner) do
        if v.category == 0 and v.type == equipData.heroType and logicMgr.HeroManager.getHeroShowLevelByPartnerId(v.partnerId) > 1 then
            curEquipData = this.GetCurrentEquipment(v.partnerId, equipData.part);
            if curEquipData == nil or curEquipData.quality < equipData.quality then
                table.insert(list, v);
            end
        end
    end
    table.sort(list, logicMgr.HeroManager.sortHero);
    return list;
end
function EquipManager.CheckOneKeyRefine(partnerId, showTip)
    local _list = logicMgr.EquipManager.getHeroEquipList(partnerId, true)
    if #_list == 0 then
        if showTip then
            UISysTips.AddMsg(getLanguage("EquipRefine_QuickRefine1"))--无可精炼装备
        end
        return false
    end
    local flag = false
    local needExp = 0
    local minEquipRefine
    for k, v in pairs(_list) do
        if v.curRfLevel < logicMgr.EquipManager.GetMaxRefineLevel(v.itemModelId) then
            local cfg = dataTable.getDataTableByMultiId("t_equiprefine", v.itemModelId, v.curRfLevel)
            if cfg then
                if needExp == 0 then
                    needExp = cfg.f_EquipRefineLevelExp
                    minEquipRefine = cfg
                elseif needExp > cfg.f_EquipRefineLevelExp then
                    needExp = cfg.f_EquipRefineLevelExp
                    minEquipRefine = cfg
                end

            end
            flag = true
            break
        end
    end
    if not flag then
        if showTip then
            UISysTips.AddMsg(getLanguage("EquipRefine_QuickRefine1"))--无可精炼装备
        end
        return false
    end
    local mapCfg = logicMgr.MapManager.getMapcfg()
    local itemList = logicMgr.ItemManager.GetRefineMatList(false);
    logicMgr.EquipManager.getEquipListByMinQuality(itemList, mapCfg.f_QuicklyRefineQuality)
    if #itemList == 0 then
        if showTip then
            UISysTips.AddMsg(getLanguage("EquipRefineTips3"))--精炼材料不足
        end
        return false
    end
    local totalExp = 0
    for k, v in pairs(itemList) do
        local exp = 0
        if v.tabType == EnumConst.ItemTableEnum.Equip then
            local cfg = dataTable.getDataTableByMultiId("t_equiprefine", v.itemModelId, v.curRfLevel or 0)
            if cfg then
                exp = cfg.f_EquipBaseExp
            end
        else
            local func = v["itemFunction"]
            exp = func[2]
        end
        exp = exp * v.num
        totalExp = totalExp + exp
    end
    if totalExp < needExp then
        if showTip then
            UISysTips.AddMsg(getLanguage("EquipRefineTips3"));--不满一级
        end
        return false
    end
    local totalMoney = needExp * minEquipRefine.f_EquipRefineGoldCo--够升一级即可
    local money = logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.MONEY)
    if money == 0 or money < totalMoney  then
        if showTip then
            UISysTips.AddMsg(string.format(getLanguage("Character_Tips19"), ItemManager.GetItemName(CurrencyEnum.MONEY)));--金币不足
        end
        return false
    end
    if RedDotsHeroWearHandler.DoGetFlag(partnerId, nil, true) == Config.RedDotsFlagState.Needful then
        if showTip then
            UISysTips.AddMsg(getLanguage("EquipRefine_QuickRefine2"))
        end
        return false
    end
    return true
end

return EquipManager